﻿using UnityEngine;
using System.Collections;
using System.IO;
public class FileHelper {


    /// <summary>
    /// 从路径获取文件名
    /// </summary>
	public static string FileNameFromUrl(string url)
    {
        return Path.GetFileName(url);
    }

    /// <summary>
    /// 文件是否存在
    /// </summary>
    public static bool FileExists(string path)
    {
        return File.Exists(path);
    }

    /// <summary>
    /// IO读取测试过可以
    /// </summary>
    public static string getPersistentPath_for_IO(string fname)
    {
        string path = string.Empty;
        if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer||
            Application.platform==RuntimePlatform.WindowsEditor)
            path = Application.persistentDataPath + "/" + fname;
        else
            path = Application.dataPath + "/Resources/" + fname;
        return path;
    }


    /// <summary>
    /// PersistentPath 不同平台路径，未测试，用做WWW读取
    /// </summary>
    public static string getPersistentPath_for_www()
    {
        string pre = "file://";
#if UNITY_EDITOR || UNITY_STANDALONE_WIN
        pre = "file:///";
#elif UNITY_ANDROID  
        pre = "file://";  
#elif UNITY_IPHONE  
        pre = "file://";  
#endif
        string path = pre + Application.persistentDataPath + "/";
        return path;
    }

  /// <summary>
  /// 读取不同平台下文件，And,iod测试过  移动端只能用WWW读取
  /// </summary>
  /// <param name="name"></param>
  /// <returns></returns>
  public static string getStreamingPath_for_www()
    {
        string folder = "";
        string pre = "file://";
#if UNITY_EDITOR
        pre = "file://";
        folder = "Android";
#elif UNITY_ANDROID  
        pre = "";  
      folder = "Android";
#elif UNITY_IPHONE  
        pre = "file://";
      folder = "IOS";
#endif
        string path = pre + Application.streamingAssetsPath ;
        return path;
    }


  public static void WriteJson(string folderName, string strB, string fileName)
  {
      string path1 = Application.persistentDataPath + "/" + folderName + "/" + fileName;
    //  UnityEngine.Debug.Log(path1);
      if (FileHelper.FileExists(path1))
      {
          File.Delete(path1);
      }
      //初始化一个  
      StreamWriter sw;
      if (Directory.Exists(Application.persistentDataPath + "/" + folderName) == false)//如果不存在就创建file文件夹
      {
          Directory.CreateDirectory(Application.persistentDataPath + "/" + folderName);
      }
      sw = File.CreateText(path1);
      //写入  
      sw.WriteLine(strB);
      //关闭  
      sw.Close();
  }

}
